package com.cy.jt.security.interceptor;

import com.cy.jt.security.util.JwtUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 令牌(token:tikcet-通票)拦截器
 * 其中,HandlerInterceptor为Spring MVC中的拦截器,可以在Controller方法执行之前之后执行一些动作
 * 1)Handler 处理器(Spring MVC中将@RestController描述的类看成时处理器)
 * 2)Interceptor  拦截器
 */
public class TokenInterceptor implements HandlerInterceptor {
    /**
     * preHandler 在目标Controller方法执行之前执行
     * @param request
     * @param response
     * @param handler   目标Controller对象
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //String token = request.getParameter("Authontication");   //请求参数
        String token = request.getHeader("Authontication");     //请求头传参
        //判定请求中是否有令牌
        if (StringUtils.hasLength("token")) throw new RuntimeException("Please Login");
        boolean flag = JwtUtils.isTokenExpired(token);
        //判定请求中是否有令牌
        if (flag) throw new RuntimeException("login timeout,please login");
        return true;   //falser表示拦截到请求以后,不再继续传递
    }
}
